package xcmg.device.service.company;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.company.CompanyApplyDO;
import xcmg.device.dao.entity.company.CompanyDealerDO;
import xcmg.device.dao.entity.company.CompanyInvitationCodeDO;
import xcmg.device.dao.entity.company.CompanySupplierDO;
import xcmg.device.dao.mapper.CompanyApplyMapper;
import xcmg.device.dao.mapper.CompanyDealerMapper;
import xcmg.device.dao.mapper.CompanyInvitationCodeMapper;
import xcmg.device.dao.mapper.CompanySupplierMapper;
import xcmg.device.infra.CompanyConstants;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.enums.ApplyStatusEnum;
import xcmg.device.infra.exception.CommonBusiExceptions;
import xcmg.device.service.basic.CommonGenService;
import xcmg.device.service.vo.company.AuditApplyVO;
import xcmg.device.service.vo.company.CompanyApplyVO;
import xcmg.device.service.vo.company.CompanyInfoVO;
import xcmg.device.service.vo.company.CompanyRegisterVO;
import xcmg.device.service.warehouse.WarehouseCompose;
import xcmg.device.util.CommonUtils;
import xcmg.device.util.CompanyUtil;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.PageHelperPlus;
import yb.ecp.fast.infra.util.Ref;
import yb.ecp.fast.infra.util.StringUtil;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by LiChangjiang on 2018/2/8 0008.
 */
@Service
@Slf4j
public class CompanyApplyService {

    private static final String DB_ERROR = "修改企业客户关系中审核状态为通过操作失败，数据库异常！";
    @Autowired
    private CompanyUtil companyUtil;
    @Autowired
    private CompanyDealerService companyDealerService;

    @Autowired
    private CompanyApplyMapper companyApplyMapper;

    @Autowired
    private CompanyDealerMapper companyDealerMapper;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private WarehouseCompose warehouseCompose;

    @Autowired
    private CompanyInvitationCodeMapper companyInvitationCodeMapper;

    @Autowired
    private CompanySupplierMapper companySupplierMapper;

    @Autowired
    private CommonGenService commonGenService;
    /**
     * 企业注册默认权限模板ID
     */
    @Value("${company.setting.registerTemplateId:2}")
    private String registerTemplateId;

    /**
     * 企业注册服务站权限模板ID
     */
    @Value("${company.setting.registerFwzTemplateId:594827971664019456}")
    private String registerFwzTemplateId;

    @Value("${company.setting.registerDls1TemplateId:594847786306895872}")
    private String registerDls1TemplateId;
    @Value("${company.setting.registerDls2TemplateId:612291032029069312}")
    private String registerDls2TemplateId;



    /**
     * 校验申请状态
     *
     * @param companyRegisterVO CompanyRegisterVO
     * @return CompanyApplyVO
     */
    public CompanyApplyVO checkApplyRecored(CompanyRegisterVO companyRegisterVO) {
        CompanyApplyDO companyApplyDO = new CompanyApplyDO();
        companyApplyDO.setOrgCode(companyRegisterVO.getOrgCode());
        companyApplyDO.setCompanyName(companyRegisterVO.getCompanyName());

        CompanyApplyDO queryRecordDO = companyApplyMapper.selectApplyRecord(companyApplyDO);
        return getVO(queryRecordDO);
    }


    private CompanyApplyVO getVO(CompanyApplyDO companyApplyDO) {
        if (null == companyApplyDO) {
            return null;
        }
        CompanyApplyVO companyApplyVO = new CompanyApplyVO();

        companyApplyVO.setApplyId(String.valueOf(companyApplyDO.getId()));
        companyApplyVO.setInvitationCode(companyApplyDO.getInvitationCode());
        companyApplyVO.setAuditId(companyApplyDO.getAuditId());
        companyApplyVO.setAuditName(companyApplyDO.getAuditName());
        companyApplyVO.setAuditRecord(companyApplyDO.getAuditRecord());
        companyApplyVO.setCompanyName(companyApplyDO.getCompanyName());
        companyApplyVO.setCreatedDate(companyApplyDO.getCreatedDate());
        companyApplyVO.setOrgCode(companyApplyDO.getOrgCode());
        companyApplyVO.setStatus(companyApplyDO.getStatus());
        companyApplyVO.setUpdateDate(companyApplyDO.getUpdateDate());
        companyApplyVO.setReceiverId(companyApplyDO.getReceiverId());
        companyApplyVO.setSenderId(companyApplyDO.getSenderId());
        companyApplyVO.setAuditId(companyApplyDO.getAuditId());

        if (ApplyStatusEnum.Pass.getCode().equals(companyApplyDO.getStatus())) {
            companyApplyVO.setStatusView(ApplyStatusEnum.Pass.getDesc());
        } else if (ApplyStatusEnum.Fail.getCode().equals(companyApplyDO.getStatus())) {
            companyApplyVO.setStatusView(ApplyStatusEnum.Fail.getDesc());
        } else {
            companyApplyVO.setStatusView(ApplyStatusEnum.Saved.getDesc());
        }

        CompanyDealerDO companyDealerDO = companyDealerMapper.itemByOrgId(companyApplyDO.getSenderId(), companyApplyDO.getReceiverId());
        if (null == companyDealerDO) {
            return companyApplyVO;
        }
        //设置下游企业名称（邀请码接收方在企业客户关系中的企业名称）
        companyApplyVO.setReceiverName(companyDealerDO.getCompanyName());

        CompanyInfoVO companyInfoVO = companyInfoService.info(companyApplyDO.getSenderId());
        if (null == companyInfoVO) {
            return companyApplyVO;
        }
        //设置邀请码发送发企业名称
        companyApplyVO.setSenderName(companyInfoVO.getCompanyName());
        return companyApplyVO;
    }


    private CompanyApplyDO getDO(CompanyApplyVO companyApplyVO) {
        if (null == companyApplyVO) {
            return null;
        }
        CompanyApplyDO companyApplyDO = new CompanyApplyDO();
        companyApplyDO.setId(CommonUtils.tryParseLong(companyApplyVO.getApplyId(),null));
        companyApplyDO.setInvitationCode(companyApplyVO.getInvitationCode());
        companyApplyDO.setAuditId(companyApplyVO.getAuditId());
        companyApplyDO.setAuditName(companyApplyVO.getAuditName());
        companyApplyDO.setAuditRecord(companyApplyVO.getAuditRecord());
        companyApplyDO.setCompanyName(companyApplyVO.getCompanyName());
        companyApplyDO.setCreatedDate(companyApplyVO.getCreatedDate());
        companyApplyDO.setOrgCode(companyApplyVO.getOrgCode());
        companyApplyDO.setStatus(companyApplyVO.getStatus());
        companyApplyDO.setUpdateDate(companyApplyVO.getUpdateDate());
        companyApplyDO.setSenderId(companyApplyVO.getSenderId());
        companyApplyDO.setReceiverId(companyApplyVO.getReceiverId());
        return companyApplyDO;
    }

    /**
     * 添加申请记录
     *
     * @param companyApplyVO CompanyApplyError
     * @return ErrorCode
     */
    public ErrorCode insert(CompanyApplyVO companyApplyVO) {
        CompanyApplyDO companyApplyDO = getDO(companyApplyVO);

        if (null == companyApplyDO) {
            return ErrorCode.IllegalArument;
        }
        int addRet = addCompanyApply(companyApplyDO);
        companyApplyVO.setId(companyApplyDO.getId());
        if (0 >= addRet) {
            return ErrorCode.CompanyApplyError;
        }
        return ErrorCode.Success;
    }

    private int addCompanyApply(CompanyApplyDO companyApplyDO) {
        companyApplyDO.setId(commonGenService.longIdWithException());
        return companyApplyMapper.insertWithPK(companyApplyDO);
    }

    /**
     * 更新申请记录信息
     *
     * @param companyApplyVO CompanyApplyVO
     * @return ErrorCode
     */
    public ErrorCode update(CompanyApplyVO companyApplyVO) {
        CompanyApplyDO companyApplyDO = getDO(companyApplyVO);

        if (null == companyApplyDO) {
            return ErrorCode.IllegalArument;
        }

        int addRet = companyApplyMapper.update(companyApplyDO);
        if (0 >= addRet) {
            return ErrorCode.CompanyApplyError;
        }
        return ErrorCode.Success;
    }

    /**
     * 查询待审核记录
     *
     * @param condition SearchCommonVO
     * @return PageCommonVO
     */
    public PageCommonVO<CompanyApplyVO> list(SearchCommonVO<CompanyApplyVO> condition) {
        PageCommonVO<CompanyApplyVO> pageCommonVO = new PageCommonVO<>();
        PageHelperPlus.orderBy("UPDATE_DATE desc");
        PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());

        List<CompanyApplyDO> doList = companyApplyMapper.list(getDO(condition.getFilters()));

        List<CompanyApplyVO> voList = new ArrayList<>();
        for (CompanyApplyDO companyApplyDO : doList) {
            voList.add(getVO(companyApplyDO));
        }
        pageCommonVO.setPageInfo(new PageInfo<CompanyApplyDO>(doList));
        pageCommonVO.setPageInfoList(voList);
        return pageCommonVO;
    }

    /**
     * 审核企业申请信息
     *
     * @param auditApplyVO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ErrorCode audit(AuditApplyVO auditApplyVO) {
        Long applyId = CommonUtils.tryParseLong(auditApplyVO.getApplyId(),0L);
        CompanyApplyDO companyApplyDO = companyApplyMapper.item(applyId);
        ErrorCode recordErt = checkRecordCondition(companyApplyDO);
        if (ErrorCode.Success != recordErt) {
            return recordErt;
        }

        companyApplyDO.setAuditId(auditApplyVO.getAuditId());
        companyApplyDO.setAuditName(auditApplyVO.getAuditName());
        companyApplyDO.setAuditRecord(auditApplyVO.getAuditRemark());
        companyApplyDO.setStatus(auditApplyVO.getAuditStatus());
        companyApplyDO.setIsBarcode(auditApplyVO.getIsBarcode());
        companyApplyDO.setIsSap(auditApplyVO.getIsSap());
        companyApplyDO.setSapCode(auditApplyVO.getSapCode());

        int updateApplyRecode = companyApplyMapper.update(companyApplyDO);
        if (0 >= updateApplyRecode) {
            LogHelper.error("更新待审核记录操作失败，数据库异常！", ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }

        if (auditApplyVO.getAuditStatus().equals(ApplyStatusEnum.Pass.getCode())) {
            //审核通过，执行企业新增流程
            return pass(companyApplyDO, auditApplyVO);
        }

        if (auditApplyVO.getAuditStatus().equals(ApplyStatusEnum.Fail.getCode())) {
            //审核拒绝，更新审核记录
            return noPass(companyApplyDO);
        }

        return ErrorCode.Success;
    }

    /**
     * 校验企业申请记录的当前状态
     *
     * @param companyApplyDO CompanyApplyDO
     * @return ErrorCode
     */
    private ErrorCode checkRecordCondition(CompanyApplyDO companyApplyDO) {
        if (null == companyApplyDO) {
            return ErrorCode.IllegalArument;
        }
        if (ApplyStatusEnum.Pass.getCode().equals(companyApplyDO.getStatus())) {
            return ErrorCode.CompanyAuditPass;//已经审核通过
        }
        if (ApplyStatusEnum.Fail.getCode().equals(companyApplyDO.getStatus())) {
            return ErrorCode.CompanyAuditFail;//已经审核拒绝
        }
        return ErrorCode.Success;
    }

    /**
     * 审核不通过<br>
     * 审核不通过，更新审核记录为“审核不通过”状态，并记录审核信息，同时修改企业客户关系为“审核不通过”
     *
     * @param companyApplyDO CompanyApplyDO
     * @return ErrorCode
     */
    private ErrorCode noPass(CompanyApplyDO companyApplyDO) {
        CompanyInvitationCodeDO invitationCodeDO = companyInvitationCodeMapper.itemByCode(companyApplyDO.getInvitationCode(), companyApplyDO.getSenderId(), companyApplyDO.getReceiverId());
        if (invitationCodeDO == null) {
            LogHelper.error("邀请码信息不存在！", ErrorCode.Failure.getCode());
            return ErrorCode.Failure;
        }
        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setCodeState(1);//邀请码状态为无效
        companyInvitationCodeDO.setInvitationCode(companyApplyDO.getInvitationCode());
        companyInvitationCodeMapper.update(companyInvitationCodeDO);

        if (invitationCodeDO.getInviteType() == 1) {
            int updateRet = companyDealerMapper.updateApplyStatus(companyApplyDO.getSenderId(), companyApplyDO.getReceiverId(), CompanyConstants.APPLY_STATUS_NO_PASS);
            if (0 >= updateRet) {
                LogHelper.error("更新企业客户关系状态为审核不通过操作失败，数据库异常！", ErrorCode.SqlSyntaxError.getCode());
                return ErrorCode.SqlSyntaxError;
            }
        } else if (invitationCodeDO.getInviteType() == 2) {
            int updateRet = companySupplierMapper.updateApplyStatus(companyApplyDO.getSenderId(), companyApplyDO.getReceiverId(), CompanyConstants.APPLY_STATUS_NO_PASS);
            if (0 >= updateRet) {
                LogHelper.error("更新企业客户关系状态为审核不通过操作失败，数据库异常！", ErrorCode.SqlSyntaxError.getCode());
                return ErrorCode.SqlSyntaxError;
            }
        }
        return ErrorCode.Success;
    }

    /**
     * 审核通过<br>
     * 审核通过，则生成企业相关初始化数据，并更新审核记录为审核通过状态，并保持审核信息，更新企业客户关系状态为审核通过
     * 企业注册成功，添加为供应商
     *
     * @param companyApplyDO CompanyApplyDO
     * @param auditApplyVO
     * @return ErrorCode
     */
    private ErrorCode pass(CompanyApplyDO companyApplyDO, AuditApplyVO auditApplyVO) {
        CompanyInfoVO companyInfoVO = new CompanyInfoVO();
        companyInfoVO.setCompanyName(companyApplyDO.getCompanyName());
        companyInfoVO.setOrgCode(companyApplyDO.getOrgCode());
        companyInfoVO.setChannel(1);
        companyInfoVO.setIsBarcode(companyApplyDO.getIsBarcode());
        companyInfoVO.setIsSap(companyApplyDO.getIsSap());
        companyInfoVO.setSapCode(companyApplyDO.getSapCode());
        companyInfoVO.setModuleTeplateId(registerTemplateId);
        if (null != auditApplyVO.getDealerType()) {
            companyInfoVO.setCompanyType(auditApplyVO.getDealerType() + "");
            //已知类型企业默认角色模板
            checkAndSetDefaultRoleTmp(auditApplyVO.getDealerType(),companyInfoVO);
        }
        Ref<String> orgIdRef = new Ref<>("");

        CompanyInvitationCodeDO invitationCodeDO = companyInvitationCodeMapper.itemByCode(companyApplyDO.getInvitationCode(), companyApplyDO.getSenderId(), companyApplyDO.getReceiverId());
        if (invitationCodeDO == null) {
            LogHelper.error("邀请码信息不存在！", ErrorCode.Failure.getCode());
            return ErrorCode.Failure;
        }
        if (invitationCodeDO.getInviteType() == 1) {
            CompanyDealerDO dealerDO = companyDealerMapper.getDealer(companyApplyDO.getSenderId(), companyApplyDO.getReceiverId());
            companyInfoVO.setCompanyType(dealerDO.getDealerType() + "");
            companyInfoVO.setDealerCode(dealerDO.getYhbh());
            companyInfoVO.setShortName(dealerDO.getShortName());
            //服务站企业默认角色模板
            checkAndSetDefaultRoleTmp(dealerDO.getDealerType(),companyInfoVO);
        }
        try {
            //新增企业信息
            ErrorCode addRet = companyInfoService.insert(companyInfoVO, orgIdRef);
            if (ErrorCode.Success != addRet) {
                LogHelper.error("审核通过新增企业信息操作失败！", addRet.getCode());
                return addRet;
            }
            if (registerFwzTemplateId.equals(companyInfoVO.getModuleTeplateId())) {
                //新增默认仓库库区储位
                warehouseCompose.addDefaultWarehouseLocationWithoutE(companyInfoVO.getOrgId());
            }
            CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
            companyInvitationCodeDO.setCodeState(1);//邀请码状态为无效
            companyInvitationCodeDO.setInvitationCode(companyApplyDO.getInvitationCode());
            companyInvitationCodeMapper.update(companyInvitationCodeDO);
            if (invitationCodeDO.getInviteType() == 1) {
                //修改企业上下游关系表中下游企业状态
                ErrorCode r = doPass1(companyApplyDO, orgIdRef);
                if (r.getCode() != ErrorCode.Success.getCode()) {
                    return r;
                }
            } else if (invitationCodeDO.getInviteType() == 2) {
                ErrorCode r = doPass2(companyApplyDO, orgIdRef);
                if (r.getCode() != ErrorCode.Success.getCode()) {
                    return r;
                }
            }
            return ErrorCode.Success;
        } catch (Exception e) {
            log.error("", e);
            throw new CommonBusiExceptions(e.getMessage());
        }
    }

    /**
     * 判断服务站赋值服务站权限
     * @param dealerType
     * @param companyInfoVO
     */
    private void checkAndSetDefaultRoleTmp(Integer dealerType, CompanyInfoVO companyInfoVO) {
        if(null==dealerType){
            return;
        }
        if (dealerType.equals(5) || dealerType.equals(50)) {
            companyInfoVO.setModuleTeplateId(registerFwzTemplateId);
        }else if (dealerType.equals(2)) {
            //代理商
            companyInfoVO.setModuleTeplateId(registerDls1TemplateId);
        }else if (dealerType.equals(20)) {
            //二级代理商
            companyInfoVO.setModuleTeplateId(registerDls2TemplateId);
        }
    }

    private ErrorCode doPass1(CompanyApplyDO companyApplyDO, Ref<String> orgIdRef) {
        int updateRet = companyDealerMapper.updateApplyStatus(companyApplyDO.getSenderId(), companyApplyDO.getReceiverId(), CompanyConstants.APPLY_STATUS_PASS);
        if (0 >= updateRet) {
            LogHelper.error(DB_ERROR, ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }
        //更新企业客户关系中绑定关系
        int boundRet = companyDealerMapper.boundDealer(orgIdRef.get(), companyApplyDO.getSenderId(), companyApplyDO.getReceiverId());
        if (0 >= boundRet) {
            LogHelper.error(DB_ERROR, ErrorCode.RelationCompanyFail.getCode());
            return ErrorCode.RelationCompanyFail;
        }
        //添加供应商关系--查询供应商信息
        CompanyInfoVO supplierInfoVO = companyInfoService.info(companyApplyDO.getSenderId());

        if (null == supplierInfoVO) {
            LogHelper.error("企业审核通过，增加供应商关系异常，上游企业信息不存在！", ErrorCode.RelationSupplierCompanyFail.getCode());
            return ErrorCode.IllegalArument;
        }
        CompanySupplierDO companySupplierDO = getSupplierDO(supplierInfoVO, orgIdRef.get());
        int insertRet = companySupplierMapper.insert(companySupplierDO);

        if (insertRet <= 0) {
            LogHelper.error("企业审核通过，增加供应商关系异常，添加供应商关系错误！", ErrorCode.RelationSupplierCompanyFail.getCode());
            return ErrorCode.RelationSupplierCompanyFail;
        }
        return ErrorCode.Success;
    }

    private ErrorCode doPass2(CompanyApplyDO companyApplyDO, Ref<String> orgIdRef) {
        int updateRet = companySupplierMapper.updateApplyStatus(companyApplyDO.getSenderId(), companyApplyDO.getReceiverId(), CompanyConstants.APPLY_STATUS_PASS);
        if (0 >= updateRet) {
            LogHelper.error(DB_ERROR, ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }
        int boundRet = companySupplierMapper.boundSupplier(orgIdRef.get(), companyApplyDO.getSenderId(), companyApplyDO.getReceiverId());
        if (0 >= boundRet) {
            LogHelper.error(DB_ERROR, ErrorCode.RelationCompanyFail.getCode());
            return ErrorCode.RelationCompanyFail;
        }
        CompanyInfoVO dealerInfo = companyInfoService.info(companyApplyDO.getSenderId());
        if (dealerInfo == null) {
            return ErrorCode.Failure;
        }
        CompanyDealerDO companyDealerDO = getCompanyDealer(dealerInfo, orgIdRef.get());

        boolean insertRet = companyDealerService.addCompanyDealerDO(companyDealerDO);

        if (!insertRet) {
            LogHelper.error("企业审核通过，增加供应商关系异常，添加供应商关系错误！", ErrorCode.RelationSupplierCompanyFail.getCode());
            return ErrorCode.RelationSupplierCompanyFail;
        }
        return ErrorCode.Success;
    }

    public CompanyDealerDO getCompanyDealer(CompanyInfoVO dealerInfo, String orgId) {
        CompanyDealerDO companyDealerDO = new CompanyDealerDO();
        companyDealerDO.setOrgId(orgId);
        companyDealerDO.setDealerOrgId(dealerInfo.getOrgId());
        companyDealerDO.setYhbh(dealerInfo.getSapCode());
        companyDealerDO.setDealerCode(dealerInfo.getDealerCode());
        companyDealerDO.setCompanyName(dealerInfo.getCompanyName());
        companyDealerDO.setShortName(dealerInfo.getShortName());
        companyDealerDO.setAddress(dealerInfo.getAddress());
        companyDealerDO.setZip(dealerInfo.getZip());
        companyDealerDO.setFax(dealerInfo.getFax());
        companyDealerDO.setContact(dealerInfo.getContact());
        companyDealerDO.setContactTel(dealerInfo.getContactTel());
        companyDealerDO.setIsPlatCompany(true);
        companyDealerDO.setPlatOrgId(dealerInfo.getOrgId());
        companyDealerDO.setCreateDate(new Date());
        companyDealerDO.setCreateId("");
        companyDealerDO.setUpdateDate(new Date());
        companyDealerDO.setUpdateId("");
        companyDealerDO.setIsDel(false);
        companyDealerDO.setDepartemntId("");
        companyDealerDO.setOwerId("");
        companyDealerDO.setApplyStatus(5);
        companyDealerDO.setIsStorage(0);
        companyDealerDO.setEnableLimit(0);
        companyDealerDO.setDealerType(CommonUtils.tryParseInt(dealerInfo.getCompanyType()));
        inputBlank(companyDealerDO,dealerInfo);
        return companyDealerDO;
    }

    private void inputBlank(CompanyDealerDO companyDealerDO, CompanyInfoVO dealerInfo) {
        if (null == dealerInfo || null == dealerInfo.getCompanyDealerVO()) {
            return;
        }
        if(StringUtils.isBlank(companyDealerDO.getOrgId())){
            companyDealerDO.setOrgId(dealerInfo.getCompanyDealerVO().getOrgId());
        }
        if(StringUtils.isBlank(companyDealerDO.getDealerOrgId())){
            companyDealerDO.setDealerOrgId(dealerInfo.getCompanyDealerVO().getDealerOrgId());
        }
        if(StringUtils.isBlank(companyDealerDO.getDealerCode())){
            companyDealerDO.setDealerCode(dealerInfo.getCompanyDealerVO().getDealerCode());
        }
        if(StringUtils.isBlank(companyDealerDO.getCompanyName())){
            companyDealerDO.setCompanyName(dealerInfo.getCompanyDealerVO().getCompanyName());
        }
        if(StringUtils.isBlank(companyDealerDO.getShortName())){
            companyDealerDO.setShortName(dealerInfo.getCompanyDealerVO().getShortName());
        }
        if(StringUtils.isBlank(companyDealerDO.getAddress())){
            companyDealerDO.setAddress(dealerInfo.getCompanyDealerVO().getAddress());
        }
        if(StringUtils.isBlank(companyDealerDO.getZip())){
            companyDealerDO.setZip(dealerInfo.getCompanyDealerVO().getZip());
        }
        if(StringUtils.isBlank(companyDealerDO.getFax())){
            companyDealerDO.setFax(dealerInfo.getCompanyDealerVO().getFax());
        }
        if(StringUtils.isBlank(companyDealerDO.getContact())){
            companyDealerDO.setContact(dealerInfo.getCompanyDealerVO().getContact());
        }
        if(StringUtils.isBlank(companyDealerDO.getContactTel())){
            companyDealerDO.setContactTel(dealerInfo.getCompanyDealerVO().getContactTel());
        }
        if(StringUtils.isBlank(companyDealerDO.getPlatOrgId())){
            companyDealerDO.setPlatOrgId(dealerInfo.getCompanyDealerVO().getPlatOrgId());
        }

        if(StringUtils.isBlank(companyDealerDO.getUpdateId())){
            companyDealerDO.setUpdateId(dealerInfo.getCompanyDealerVO().getUpdateId());
        }
        if(StringUtils.isBlank(companyDealerDO.getDepartemntId())){
            companyDealerDO.setDepartemntId(dealerInfo.getCompanyDealerVO().getDepartemntId());
        }
        if(StringUtils.isBlank(companyDealerDO.getOwerId())){
            companyDealerDO.setOwerId(dealerInfo.getCompanyDealerVO().getOwerId());
        }
        if(StringUtils.isBlank(companyDealerDO.getCustomerGroup())){
            companyDealerDO.setCustomerGroup(dealerInfo.getCompanyDealerVO().getCustomerGroup());
        }
        if(StringUtils.isBlank(companyDealerDO.getPriceGroup())){
            companyDealerDO.setPriceGroup(dealerInfo.getCompanyDealerVO().getPriceGroup());
        }
        if(StringUtils.isBlank(companyDealerDO.getSaleGroup())){
            companyDealerDO.setSaleGroup(dealerInfo.getCompanyDealerVO().getSaleGroup());
        }
        if(StringUtils.isBlank(companyDealerDO.getSaleDept())){
            companyDealerDO.setSaleDept(dealerInfo.getCompanyDealerVO().getSaleDept());
        }
        if(StringUtils.isBlank(companyDealerDO.getDealerActiveId())){
            companyDealerDO.setDealerActiveId(dealerInfo.getCompanyDealerVO().getDealerActiveId());
        }
        if(StringUtils.isBlank(companyDealerDO.getDealerLevelId())){
            companyDealerDO.setDealerLevelId(dealerInfo.getCompanyDealerVO().getDealerLevelId());
        }
        if(StringUtils.isBlank(companyDealerDO.getDealerLevelName())){
            companyDealerDO.setDealerLevelName(dealerInfo.getCompanyDealerVO().getDealerLevelName());
        }
        if(StringUtils.isBlank(companyDealerDO.getDeptId())){
            companyDealerDO.setDeptId(dealerInfo.getCompanyDealerVO().getDeptId());
        }
        if(StringUtils.isBlank(companyDealerDO.getDeptName())){
            companyDealerDO.setDeptName(dealerInfo.getCompanyDealerVO().getDeptName());
        }
        if(StringUtils.isBlank(companyDealerDO.getCountry())){
            companyDealerDO.setCountry(dealerInfo.getCompanyDealerVO().getCountry());
        }
        if(StringUtils.isBlank(companyDealerDO.getMarketingCenterCode())){
            companyDealerDO.setMarketingCenterCode(dealerInfo.getCompanyDealerVO().getMarketingCenterCode());
        }
        if(StringUtils.isBlank(companyDealerDO.getMarketingCenterName())){
            companyDealerDO.setMarketingCenterName(dealerInfo.getCompanyDealerVO().getMarketingCenterName());
        }
        if(StringUtils.isBlank(companyDealerDO.getMarketingCenterCode2())){
            companyDealerDO.setMarketingCenterCode2(dealerInfo.getCompanyDealerVO().getMarketingCenterCode2());
        }
        if(StringUtils.isBlank(companyDealerDO.getMarketingCenterName2())){
            companyDealerDO.setMarketingCenterName2(dealerInfo.getCompanyDealerVO().getMarketingCenterName2());
        }
        if(StringUtils.isBlank(companyDealerDO.getZb())){
            companyDealerDO.setZb(dealerInfo.getCompanyDealerVO().getZb());
        }
        if(StringUtils.isBlank(companyDealerDO.getDetailAddr())){
            companyDealerDO.setDetailAddr(dealerInfo.getCompanyDealerVO().getDetailAddr());
        }
        if(StringUtils.isBlank(companyDealerDO.getYhbh())){
            companyDealerDO.setYhbh(dealerInfo.getCompanyDealerVO().getYhbh());
        }
        if(StringUtils.isBlank(companyDealerDO.getYhmc())){
            companyDealerDO.setYhmc(dealerInfo.getCompanyDealerVO().getYhmc());
        }
    }


    public CompanySupplierDO getSupplierDO(CompanyInfoVO companyInfoVO, String orgId) {
        CompanySupplierDO companySupplierDO = new CompanySupplierDO();
        companySupplierDO.setOrgId(orgId);
        companySupplierDO.setSupplierOrgId(companyInfoVO.getOrgId());
        if (StringUtils.isNotBlank(companyInfoVO.getDealerCode())) {
            companySupplierDO.setSupplierCode(companyInfoVO.getDealerCode());
        } else {
            companySupplierDO.setSupplierCode(companyInfoVO.getOrgCode());
        }

        companySupplierDO.setCompanyName(companyInfoVO.getCompanyName());
        companySupplierDO.setShortName(companyInfoVO.getShortName());
        companySupplierDO.setAddress(companyInfoVO.getAddress());
        companySupplierDO.setZip(companyInfoVO.getZip());
        companySupplierDO.setFax(companyInfoVO.getFax());
        companySupplierDO.setContact(companyInfoVO.getContact());
        companySupplierDO.setContactTel(companyInfoVO.getContactTel());
        companySupplierDO.setIsPlatCompany(true);
        companySupplierDO.setPlatOrgId(companyInfoVO.getOrgId());
        companySupplierDO.setCreateDate(new Date());
        companySupplierDO.setUpdateDate(new Date());
        companySupplierDO.setIsDel(false);
        companySupplierDO.setApplyStatus(5);
        //判断“是否区域内”
        boolean intraregional = checkSameIntraregional(orgId, companyInfoVO.getOrgId());
        companySupplierDO.setIntraregional(intraregional ? 1 : 0);
        return companySupplierDO;
    }

    private boolean checkSameIntraregional(String sourceOrgId, String targetOrgId) {
        CompanyDealerDO d1 = companyDealerMapper.itemByPlatOrgId(sourceOrgId);
        CompanyDealerDO d2 = companyDealerMapper.itemByPlatOrgId(targetOrgId);
        if (null == d1 || null == d2) {
            return false;
        }
        if (StringUtils.isNotBlank(d1.getMarketingCenterCode())
                && StringUtils.isNotBlank(d2.getMarketingCenterCode())
                && d1.getMarketingCenterCode().equals(d2.getMarketingCenterCode())
        ) {
            return true;
        }

        if (StringUtils.isNotBlank(d1.getMarketingCenterCode())
                && StringUtils.isNotBlank(d2.getMarketingCenterCode2())
                && d1.getMarketingCenterCode().equals(d2.getMarketingCenterCode2())
        ) {
            return true;
        }

        if (StringUtils.isNotBlank(d1.getMarketingCenterCode2())
                && StringUtils.isNotBlank(d2.getMarketingCenterCode())
                && d1.getMarketingCenterCode2().equals(d2.getMarketingCenterCode())
        ) {
            return true;
        }

        if (StringUtils.isNotBlank(d1.getMarketingCenterCode2())
                && StringUtils.isNotBlank(d2.getMarketingCenterCode2())
                && d1.getMarketingCenterCode2().equals(d2.getMarketingCenterCode2())
        ) {
            return true;
        }
        return false;
    }


    /**
     * 通过邀请码绑定企业客户关系<br>
     * 更新邀请码状态无效，修改企业客户关系表状态为审核通过，绑定客户关系
     *
     * @param companyApplyVO CompanyApplyVO
     * @param orgId          orgId
     * @return ErrorCode
     */
    public ErrorCode boundDealer(CompanyApplyVO companyApplyVO, String orgId) {
        if (companyApplyVO == null) {
            return ErrorCode.IllegalArument;
        }
        //校验邀请码是否合法
        CompanyInvitationCodeDO inviteInfo = companyInfoService.queryInviteInfo(companyApplyVO.getInvitationCode());

        if (null == inviteInfo) {
            return ErrorCode.InvitationCodeFail;
        }
        if (StringUtil.isNullOrEmpty(companyApplyVO.getInvitationCode())) {
            return ErrorCode.IllegalArument;
        }
        if (inviteInfo.getInviteType() != 1) {
            return ErrorCode.InvitationCodeFail;
        }

        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setInvitationCode(companyApplyVO.getInvitationCode());
        companyInvitationCodeDO = companyInvitationCodeMapper.invitationInfo(companyInvitationCodeDO);

        companyInvitationCodeDO.setCodeState(1);//邀请码状态为无效
        companyInvitationCodeMapper.update(companyInvitationCodeDO);

        //修改企业上下游关系表中下游企业状态
        int updateRet = companyDealerMapper.updateApplyStatus(companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_PASS);
        if (0 >= updateRet) {
            LogHelper.error(DB_ERROR, ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }

        //更新企业客户关系中绑定关系
        int boundRet = companyDealerMapper.boundDealer(orgId, companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId());
        if (0 >= boundRet) {
            LogHelper.error("修改企业客户关系中绑定下游企业操作失败，数据库异常！", ErrorCode.RelationCompanyFail.getCode());
            return ErrorCode.RelationCompanyFail;
        }
        CompanyInfoVO companyInfoVO = companyInfoService.info(companyInvitationCodeDO.getSenderOrgId());
        CompanySupplierDO companySupplierDO = getSupplierDO(companyInfoVO, orgId);
        companySupplierMapper.insert(companySupplierDO);
        return ErrorCode.Success;
    }

    /**
     * 通过邀请码绑定企业下游关系<br>
     * 更新邀请码状态无效，修改企业客户关系表状态为审核通过，绑定客户关系
     *
     * @param companyApplyVO CompanyApplyVO
     * @param orgId          orgId
     * @return ErrorCode
     */
    public ErrorCode boundSupplier(CompanyApplyVO companyApplyVO, String orgId) {
        if (null == companyApplyVO) {
            return ErrorCode.IllegalArument;
        }
        //校验邀请码是否合法
        CompanyInvitationCodeDO inviteInfo = companyInfoService.queryInviteInfo(companyApplyVO.getInvitationCode());
        if (null == inviteInfo) {
            return ErrorCode.InvitationCodeFail;
        }

        if (StringUtil.isNullOrEmpty(companyApplyVO.getInvitationCode())) {
            return ErrorCode.IllegalArument;
        }
        if (inviteInfo.getInviteType() != 2) {
            return ErrorCode.InvitationCodeFail;
        }

        CompanyInvitationCodeDO companyInvitationCodeDO = new CompanyInvitationCodeDO();
        companyInvitationCodeDO.setInvitationCode(companyApplyVO.getInvitationCode());
        companyInvitationCodeDO = companyInvitationCodeMapper.invitationInfo(companyInvitationCodeDO);

        companyInvitationCodeDO.setCodeState(1);//邀请码状态为无效
        companyInvitationCodeMapper.update(companyInvitationCodeDO);

        //修改企业上下游关系表中下游企业状态
        int updateRet = companySupplierMapper.updateApplyStatus(companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId(), CompanyConstants.APPLY_STATUS_PASS);
        if (0 >= updateRet) {
            LogHelper.error(DB_ERROR, ErrorCode.SqlSyntaxError.getCode());
            return ErrorCode.SqlSyntaxError;
        }

        //更新企业客户关系中绑定关系
        int boundRet = companySupplierMapper.boundSupplier(orgId, companyInvitationCodeDO.getSenderOrgId(), companyInvitationCodeDO.getReceiverOrgId());
        if (0 >= boundRet) {
            LogHelper.error("修改企业客户关系中绑定下游企业操作失败，数据库异常！", ErrorCode.RelationCompanyFail.getCode());
            return ErrorCode.RelationCompanyFail;
        }
        CompanyInfoVO companyInfoVO = companyInfoService.info(companyInvitationCodeDO.getSenderOrgId());
        CompanyDealerDO companyDealerDO = getCompanyDealer(companyInfoVO, orgId);
        companyDealerService.addCompanyDealerDO(companyDealerDO);
        return ErrorCode.Success;
    }

}
